﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace PropertyGridEx
{
    using System;
    using System.ComponentModel;
    using System.Drawing.Design;
    using System.Runtime.CompilerServices;
    using System.Windows.Forms;

    public class UIFolderEditor : System.Drawing.Design.UITypeEditor
    {
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            if (context != null && context.Instance != null)
            {
                if (!context.PropertyDescriptor.IsReadOnly)
                {
                    return UITypeEditorEditStyle.Modal;
                }
            }
            return UITypeEditorEditStyle.None;
        }

        [RefreshProperties(RefreshProperties.All)]
        public override object EditValue(ITypeDescriptorContext context, System.IServiceProvider provider, object value)
        {
            if (context == null || provider == null || context.Instance == null)
            {
                return base.EditValue(provider, value);
            }

            FolderBrowserDialog folderDlg = new FolderBrowserDialog();
            folderDlg.Description = "Select " + context.PropertyDescriptor.DisplayName;

            FolderBrowserPathAttribute pathAtt = (FolderBrowserPathAttribute)context.PropertyDescriptor.Attributes[typeof(FolderBrowserPathAttribute)];
            if (pathAtt != null)
            {
                folderDlg.SelectedPath = pathAtt.SelectedPath;
            }
            folderDlg.RootFolder = Environment.SpecialFolder.MyComputer;
            if (folderDlg.ShowDialog() == DialogResult.OK)
            {
                value = folderDlg.SelectedPath;
            }
            folderDlg.Dispose();
            return value;
        }

        public class FolderBrowserPathAttribute : Attribute
        {
            private string _path;

            public string SelectedPath
            {
                get { return this._path; }
            }

            public FolderBrowserPathAttribute(string value)
                : base()
            {
                this._path = value;
            }
        }
    }
}

